import 'dart:convert';

import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:intl/intl.dart';
import 'package:leader_doctor_flutter/common/data/app.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/common/widget/refresh_custom_widget.dart';
import 'package:leader_doctor_flutter/common/widget/table_placeholder_widget.dart';
import 'package:leader_doctor_flutter/styles/colors.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../common/http/api.dart';
import '../../../common/http/http_client.dart';
import '../../../common/utils/image_utils.dart';
import '../../../model/sign_history.dart';
import '../../../plugins/plugins_messages.g.dart';

/// @Author lixiaobin
/// @Date 2023/11/13
/// @Description 签约记录
class SignHistoryPage extends StatefulWidget {
  const SignHistoryPage({super.key});

  @override
  State<SignHistoryPage> createState() => _SignHistoryPageState();
}

class _SignHistoryPageState extends State<SignHistoryPage> {
  var pageSize = 20;
  var pageNo = 1;
  var preTimeStr = '';
  bool dataLoaded = false; // 数据请求中
  List<SignHistoryModel> items = [];
  final _payStatusMap = {'toPay': '待支付', 'setup': '签约成功', 'remove': '签约结束', 'cancel': '患者取消支付'};

  final RefreshController _refreshController = RefreshController(initialRefresh: false);

  void _onRefresh() async {
    pageNo = 1;
    _getSignHistory();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    pageNo++;
    _getSignHistory();
    _refreshController.loadComplete();
  }

  @override
  void initState() {
    super.initState();
    _getSignHistory();
  }

  @override
  Widget build(BuildContext context) {
    //根据时间分组
    var groupList = groupBy(items, (value) {
      return DateFormat('yyyy-MM-dd').format(DateFormat('yyyy-MM-dd hh:mm:ss').parse(value.createTime ?? ''));
    });
    return Scaffold(
      appBar: CommWidget.getCommAppbar(context),
      body: SmartRefresher(
        controller: _refreshController,
        enablePullDown: true,
        enablePullUp: true,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: dataLoaded
            ? (groupList.isEmpty
                ? TablePlaceholderWidget(
                    message: "暂无数据",
                    yOffset: -30,
                  )
                : ListView.builder(
                    itemCount: groupList.length,
                    shrinkWrap: true,
                    itemBuilder: (c, i) => _buildTitleItem(i, groupList),
                  ))
            : Container(),
      ),
    );
  }

  _getSignHistory() async {
    var user = App.instance.userInfo;
    var httpRequest = HttpRequest(Api.signHistory, body: {
      'userId': user?.id,
      "pageIndex": pageNo.toString(),
    });
    var httpResponse = await HttpClient.post(httpRequest);
    var map = jsonDecode(utf8.decode(httpResponse.raw!.bodyBytes));
    print("签约列表 = $map, userId = ${user?.id}");
    var tmpList = ((map['responseBody'] as List?) ?? []).map((e) => SignHistoryModel.fromJson(e)).toList();
    pageNo == 1 ? items = tmpList : items.addAll(tmpList);
    setState(() {
      dataLoaded = true;
    });
  }

  /// 时间标题
  Widget _buildTitleItem(int index, Map<String, List<SignHistoryModel>> map) {
    var timeStr = map.keys.toList()[index];
    var modelList = map[timeStr];
    return Column(
      children: [
        Container(
            height: 35.w,
            alignment: Alignment.centerLeft,
            color: ColorRes.colorEEF2F5,
            padding: EdgeInsets.only(left: 18.w),
            child: Text(
              timeStr,
              style: TextStyle(
                color: ColorRes.color353535,
                fontSize: 16.sp,
              ),
            )),
        // ListView.builder(
        //   shrinkWrap: true,
        //   physics: const NeverScrollableScrollPhysics(),
        //   itemBuilder: (c, i) => _buildItem(modelList?[i]),
        //   itemCount: modelList?.length,
        // )
        ...modelList?.map((model) => _buildItem(model)).toList() ?? [],
      ],
    );
  }

  /// 内容
  Widget _buildItem(SignHistoryModel? item) {
    var container = Container(
      height: 80.w,
      width: double.infinity,
      color: ColorRes.colorFFFFFF,
      alignment: Alignment.centerLeft,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Visibility(
            child: Container(
              height: 1.w,
              alignment: Alignment.centerLeft,
              color: ColorRes.colorEEF2F5,
            ),
          ),
          Expanded(
              child: Row(
            children: [
              SizedBox(
                width: 20.w,
              ),
              ImageLoader.loadPatientAvatar(item?.headIcon ?? '', size: Size(45.w, 45.w)),
              SizedBox(
                width: 14.w,
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(
                          width: 70.w,
                          child: Text(
                            item?.patientIdcard?.name ?? '未知',
                            softWrap: false,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(color: ColorRes.color353535, fontSize: 16.sp),
                          ),
                        ),
                        SizedBox(
                          width: 5.w,
                        ),
                        Text(
                          item?.patientIdcard?.sex == '1' ? '男' : '女',
                          style: TextStyle(color: ColorRes.color999999, fontSize: 16.sp),
                        ),
                        SizedBox(
                          width: 5.w,
                        ),
                        Text(
                          '${item?.patientIdcard?.age ?? '0'}岁',
                          style: TextStyle(color: ColorRes.color999999, fontSize: 16.sp),
                        ),
                      ]),
                  SizedBox(
                    height: 8.w,
                  ),
                  Text('发起医生  ${item?.initiatorDoctor?.name ?? ''}',
                      style: TextStyle(color: ColorRes.color999999, fontSize: 16.sp))
                ],
              ),
              Expanded(
                  child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Container(
                      width: 5.w,
                      height: 5.w,
                      decoration: BoxDecoration(
                          color: item?.signStatus != 'setup' ? ColorRes.colorFA3C55 : ColorRes.color02D3A9,
                          borderRadius: BorderRadius.circular(2.5.w))),
                  SizedBox(
                    width: 5.w,
                  ),
                  Text(_payStatusMap[item?.signStatus] ?? '',
                      style: TextStyle(color: ColorRes.color999999, fontSize: 16.sp)),
                  SizedBox(
                    width: 15.w,
                  )
                ],
              ))
            ],
          ))
        ],
      ),
    );
    return container;
  }
}
